package com.ruoyi.student_club.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.student_club.domain.Club;
import com.ruoyi.student_club.dto.ClubAppDto;
import com.ruoyi.student_club.dto.ClubDto;
import com.ruoyi.student_club.mapper.ClubMemberMapper;
import com.ruoyi.student_club.mapper.ClubPosterMapper;
import com.ruoyi.student_club.utils.UploadUtil;
import com.ruoyi.student_club.vo.ClubVo;
import com.ruoyi.student_club.vo.RecommendVo;
import com.ruoyi.student_club.vo.app.ClubDetailVo;
import com.ruoyi.student_club.vo.app.ClubListVo;
import com.ruoyi.student_club.vo.app.ClubPictureVo;
import com.ruoyi.student_club.vo.app.ClubRecommendVo;
import org.springframework.stereotype.Service;
import com.ruoyi.student_club.mapper.ClubMapper;
import com.ruoyi.student_club.service.IClubService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 社团列表展示Service业务层处理
 *
 * @author 无尤
 * @date 2022-01-14
 */
@Service
public class ClubServiceImpl extends ServiceImpl<ClubMapper, Club> implements IClubService {

    @Resource
    ClubMapper clubMapper;

    @Resource
    ClubMemberMapper memberMapper;

    @Resource
    ClubPosterMapper posterMapper;

    /**
     * 获取社团列表
     *
     * @param page     分页信息
     * @param typeName 社团类型
     * @param clubName 社团名称
     * @return 社团列表
     */
    @Override
    public Page<ClubVo> queryPage(Page<ClubVo> page, String typeName, String clubName) {
        return baseMapper.queryPage(page, null, typeName, clubName);
    }

    /**
     * 社团详情
     *
     * @param page 分页信息
     * @return
     */
    @Override
    public Page<ClubVo> queryPage(Page<ClubVo> page) {
        //获取社团信息
        SysUser current = ShiroUtils.getSysUser();
        Long clubId = current.getClubId();
        return baseMapper.queryPage(page, clubId, null, null);
    }

    /**
     * 新增社团
     *
     * @param clubDto 社团信息对象
     * @return 状态
     */
    @Override
    public void save(ClubDto clubDto) {
        boolean status = checkName(clubDto);
        if (status) {
            Club club = new Club();
            club.setClubName(clubDto.getClubName());
            club.setAvatar(clubDto.getAvatar());
            club.setIntroduce(clubDto.getIntroduce());
            club.setTypeId(clubDto.getTypeId());
            club.setReader(0);
            clubMapper.insert(club);
        }
    }

    /**
     * 修改社团
     *
     * @param clubDto 社团信息
     */
    @Override
    public void update(ClubDto clubDto) {
        //除自身外
        List<Club> clubList = clubMapper.selectList(new QueryWrapper<Club>().ne("club_id", clubDto.getClubId()));
        for (Club club : clubList) {
            if (club.getClubName().equals(clubDto.getClubName())) {
                throw new RuntimeException("社团已存在，请重新命名！");
            }
        }
        Club club = new Club();
        BeanUtils.copyBeanProp(club, clubDto);
        //删除服务器上的原图片
        Club selectById = baseMapper.selectById(clubDto.getClubId());
        String path = setAvatar(selectById.getAvatar());
        if (path.equals(clubDto.getAvatar())) {
            club.setAvatar(null);
        } else {
            try {
                UploadUtil.deletePicture(selectById.getAvatar());
            } catch (Exception e) {
                throw new RuntimeException("图片更新失败");
            }
        }
        clubMapper.updateById(club);
    }


    /**
     * 删除社团
     *
     * @param clubId 社团id
     */
    @Override
    public void remove(Long clubId) {
        Club club = clubMapper.selectById(clubId);
        if (club == null) {
            throw new RuntimeException("此社团不存在");
        }
        String path = club.getAvatar();
        UploadUtil.deletePicture(path);
        clubMapper.deleteById(clubId);
    }


    public boolean checkName(ClubDto clubDto) {
        List<Club> clubList = clubMapper.selectList(new QueryWrapper<>());
        for (Club club : clubList) {
            if (club.getClubName().equals(clubDto.getClubName())) {
                throw new RuntimeException("社团已存在，请重新命名！");
            }
        }
        return true;
    }

    /**
     * 获取社团推荐列表
     *
     * @return
     */
    @Override
    public List<ClubRecommendVo> getClubRecommendList() {
        List<ClubRecommendVo> clubRecommendList = clubMapper.getClubRecommendList();
        if (clubRecommendList.size() == 0) {
            throw new RuntimeException("请先添加社团推荐");
        }
        //获取社团人数
        for (ClubRecommendVo vo : clubRecommendList) {
            int num = memberMapper.getPeople(vo.getClubId());
            vo.setPeople(num);
        }
        return clubRecommendList;
    }

    /**
     * 获取社团详情（app）
     *
     * @param clubId 社团id
     * @return
     */
    @Override
    public ClubDetailVo getClubDetail(Long clubId) {
        if (clubId == null || clubId <= 0) {
            throw new RuntimeException("传值错误，存在sql植入风险，计入日志");
        }
        ClubDetailVo detail = clubMapper.getClubDetail(clubId);
        if (detail == null) {
            throw new RuntimeException("此社团|协会不存在！");
        }
        //获取加入的人数
        int people = memberMapper.getPeople(clubId);
        detail.setPeople(people);
        //获取相册,若为空则放置头像
        List<ClubPictureVo> pictureList = posterMapper.getClubPictureList(clubId);
        if (pictureList.size() == 0) {
            ClubPictureVo pictureVo = new ClubPictureVo();
            pictureVo.setPosterPath(detail.getAvatar());
            pictureList.add(pictureVo);
        }
        detail.setClubPictureVoList(pictureList);
        return detail;
    }

    /**
     * 获取社团列表
     *
     * @return
     */
    @Override
    public PageInfo getClubList(ClubAppDto dto) {
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        PageHelper.startPage(dto.getPage(), dto.getSize());
        List<ClubListVo> clubList = clubMapper.getClubList(dto);
        for (ClubListVo clubListVo : clubList) {
            int people = memberMapper.getPeople(clubListVo.getClubId());
            clubListVo.setPeople(people);
        }
        PageInfo pageInfo = new PageInfo(clubList);
        return pageInfo;
    }

    /**
     * 获取社团列表（添加推荐时展示）
     * @return
     */
    @Override
    public List<RecommendVo> clubList() {
        return clubMapper.clubList();
    }

    /**
     * 点击社团，浏览数 +1
     * @param clubId 社团id
     */
    @Override
    public void updateRead (Long clubId){
        if (clubId == null || clubId <= 0){
            throw new RuntimeException("存在注入风险！！！");
        }
        Integer readerNum = clubMapper.getReaderNum(clubId);
        if (readerNum == null){
            clubMapper.updateRead(1,clubId);
        }
        clubMapper.updateRead(readerNum + 1,clubId);
    }


    /**
     * 地址转换
     * @param avatar
     * @return
     */
    public String setAvatar(String avatar) {
        if (avatar != null && avatar.contains("upload")){
            avatar = avatar.substring(avatar.indexOf("upload")-1);
        }
        return avatar;
    }

}
